// hooks/sheet.ts
import { useCallback } from 'react';

export const useSheet = (locale: Locales) => {
  // 加载数据表列表
  const loadSheets = useCallback(async () => {
    try {
      const sheetList = await Dingdocs.script.run('getAllSheets');
      return sheetList;
    } catch (error: any) {
      console.error('Load sheets failed:', error);
      throw error;
    }
  }, []);

  // 加载当前激活的数据表
  const loadActiveSheet = useCallback(async () => {
    try {
      const sheet = await Dingdocs.script.run('getActiveSheet');
      return sheet;
    } catch (error: any) {
      console.error('Load active sheet failed:', error);
      throw error;
    }
  }, []);

  // 创建数据表
  const handleCreateSheet = useCallback(async (loadSheetsFn: () => Promise<void>) => {
    const name = prompt(locale.enterSheetName);
    if (!name || !name.trim()) {
      return;
    }

    try {
      await Dingdocs.script.run('createSheet', name.trim());
      console.log(`✅ ${locale.createSheetSuccess}`);
      await loadSheetsFn();
    } catch (error: any) {
      alert(`${locale.operationFailed}: ${error.message}`);
    }
  }, [locale]);

  // 删除数据表
  const handleDeleteSheet = useCallback(async (
    sheetId: string, 
    sheetName: string, 
    loadSheetsFn: () => Promise<void>,
    loadActiveSheetFn: () => Promise<void>,
    activeSheet: Sheet | null
  ) => {
    if (!window.confirm(`${locale.confirmDelete}: ${sheetName}?`)) {
      return;
    }

    try {
      await Dingdocs.script.run('deleteSheet', sheetId);
      console.log(`✅ ${locale.deleteSheetSuccess}`);
      await loadSheetsFn();
      if (activeSheet?.id === sheetId) {
        await loadActiveSheetFn();
      }
    } catch (error: any) {
      alert(`${locale.operationFailed}: ${error.message}`);
    }
  }, [locale]);

  return {
    loadSheets,
    loadActiveSheet,
    handleCreateSheet,
    handleDeleteSheet
  };
};